/**
 * 全局响应拦截器
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  HttpStatus,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface Response<T> {
  code: number;
  result: T;
  message: string;
  timestamp: number;
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    const ctx = context.switchToHttp();
    const response = ctx.getResponse();
    const statusCode = response.statusCode;

    return next.handle().pipe(
      map(result => {
        // 处理不同的状态码
        let message = 'success';
        if (statusCode === HttpStatus.CREATED) {
          message = '创建成功';
        } else if (statusCode === HttpStatus.NO_CONTENT) {
          message = '删除成功';
        }

        return {
          code: 0,
          result,
          message,
          timestamp: Date.now(),
        };
      }),
    );
  }
} 